<!-- 转账钱包汇总 -->
<template>
  <SearchTable :query="data.query" :list="data.list" :total="data.total" :showPanel="false" :showExport="true"
    @download="getSearchList('export')" @search="getSearchList" @reset="onHideDetails(true)" @changeTh="data.dialogVisible = true">
    <template #form>
      <el-form-item label="商户类别：" v-if="!indexStore.is_general_agent">
        <el-select v-model="data.query.operated_id" placeholder="请选择" filterable @change="getSearchAgentList">
          <el-option label="全部" :value="-1"/>
          <el-option class="flexBetween" v-for="item in data.OperatedArray" :key="item.value" :label="'【' + item.value + '】' + item.label"
            :value="item.value" >
            【{{ item.value }}】{{ item.label }}
            <div>
              <el-tag size="small" v-if="item.type==1" type="danger" class="marginR2" style="font-size:10px;">测试</el-tag>
              <el-tag size="small" :type="item.value==1?'success':item.currency==1?'danger':'warning'" style="font-size:10px;">
                {{ item.value==1?'直营':item.currency==1?'多货币':'正常总代' }}
              </el-tag>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商户：">
      <el-select v-model="data.query.agent_id" placeholder="请选择" filterable @change="getSearchAgentOperatedList">
        <el-option label="全部" :value="-1"/>
        <el-option v-for="item in data.commercialArray" :key="item.value" :label="'【' + item.value + '】' + item.label"
          :value="item.value" v-show="!item.type || item.type">
          <span v-if="!indexStore.is_general_agent">【{{ item.value }}】{{ item.label }}</span>
          <span v-else>
            【{{ item.value }}】{{ item.label }}
            ({{ selectToLabel(indexStore.currentArray, selectToLabel(indexStore.agentArray, item.value,'currency','value')) }})
          </span>
        </el-option>
      </el-select>
    </el-form-item>
      <el-form-item label="日期时间：">
        <el-date-picker v-model="data.query.date" type="daterange" range-separator="-" start-placeholder="请选择开始时间"
          end-placeholder="请选择结束时间" value-format="YYYY-MM-DD" :clearable="false" :disabled-date="indexStore.disabledDateTime"/>
      </el-form-item>
    </template>
    <template #button>
      <el-button :type="data.dayIndex == 1 ? 'success' : ''" :disabled="indexStore.loading"
          @click="changeTime(1)">今日</el-button>
        <el-button :type="data.dayIndex == 2 ? 'success' : ''" :disabled="indexStore.loading"
          @click="changeTime(2)">昨日</el-button>
        <el-button :type="data.dayIndex == 3 ? 'success' : ''" :disabled="indexStore.loading"
          @click="changeTime(3)">上周</el-button>
        <el-button :type="data.dayIndex == 4 ? 'success' : ''" :disabled="indexStore.loading"
          @click="changeTime(4)">本周</el-button>
        <el-button :type="data.dayIndex == 5 ? 'success' : ''" :disabled="indexStore.loading"
          @click="changeTime(5)">本月</el-button>
        <el-button :type="data.dayIndex == 6 ? 'success' : ''" :disabled="indexStore.loading"
          @click="changeTime(6)">上月</el-button>
      <el-button type="warning" @click="data.query.is_usdt_show = !data.query.is_usdt_show, getSearchList()">{{
        data.query.is_usdt_show ? '取消换算' :'换算USDT' }}</el-button>
    </template>
    <template #table>
      <template v-for="(item, index) in data.fields" :key="index">
        <el-table-column v-if="item.visible" :prop="item.prop" :label="item.label" :width="item.width" show-overflow-tooltip>
          <template #header>
            <el-tooltip v-if="item.tips" effect="dark" placement="top">
              <template #content>
                {{ item.tips }}
              </template>
              <el-icon class="ques-tips">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
            {{ item.label }}
          </template>
          <template v-if="item.prop == 'agent_id'" #default="scope">
            {{ selectToLabel(indexStore.agentArray, scope.row.agent_id) }}
          </template>
        </el-table-column>
      </template>
      <el-table-column fixed="right" label="操作" width="100">
        <template #header>
          <el-tooltip effect="dark" content="查看此条记录详情日志描述" placement="top">
            <el-icon class="ques-tips">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
          详情
        </template>
        <template #default="scope">
          <el-button type="success" v-permiss="'/system/destroyManager'" size="small" @click="checkDetails(scope.row)">
            详情
          </el-button>
        </template>
      </el-table-column>
    </template>
  </SearchTable>

  <!-- 变更表头弹框 -->
  <tableHeader :dialogVisible="data.dialogVisible" :list="data.fields" @cancel="data.dialogVisible = false"
    @resetData="resetData" />

  <!-- 转账钱包详情 -->
  <el-dialog v-model="data.isShowDetails" width="65%" title="" :close-on-click-modal="false" top="12vh"
    :close-on-press-escape="false" @close="onHideDetails">
    <template #header>
      <p class="box-title mustPass">
        【{{ data.checkedItem.agent_id }}】 {{ selectToLabel(indexStore.agentArray, data.checkedItem.agent_id) }}
        <span style="color: #666666;">{{ data.checkedItem.currency }}</span>
      </p>
    </template>
    <div v-loading="indexStore.moduleLoading" class="dialogMaxHeight">
      <SearchTable :query="data.query" :list="data.listDetails" :total="data.totalDetails" @changeSize="changeSize" @changePage="changePage" :showForm="false" :showSet="false" @reset="onHideDetails(true)">
        <template #form></template>
        <template #table>
          <template v-for="(item, index) in data.fieldDetails" :key="index">
            <el-table-column v-if="item.visible" :prop="item.prop" :label="item.label" :width="item.width">
              <template #header>
                <el-tooltip v-if="item.tips" effect="dark" placement="top">
                  <template #content>
                    {{ item.tips }}
                  </template>
                  <el-icon class="ques-tips">
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
                {{ item.label }}
              </template>
              <template v-if="item.prop == 'account3d'" #default="scope">
                <span class="item_details" @click="checkUser(scope.row)">
                  {{ scope.row.account3d }}
                </span>
              </template>
            </el-table-column>
          </template>
        </template>
      </SearchTable>
    </div>
  </el-dialog>
  <!-- 玩家信息详情 -->
  <UserDetails :show="data.isUserDetails" @onHideDetails="onHideDetails" :checkedItem="data.checkedUserItem" />
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import tableHeader from '@/components/tableHeader/tableHeader.vue'
import SearchTable from '@/components/SearchTable/SearchTable.vue'
import UserDetails from '@/views/player/components/user-details.vue'
import { exportToExcel } from '@/utils/export'
import { throttle, selectToLabel, CurrencyExchange, AgentCurrency } from '@/utils/index'
import { getDateDay, getWeek, getMonth, setTimeValue } from '@/utils/time'
import { BigWan, BigTimes, BigMinus } from '@/utils/math'
import { getGeneralAgent } from '@/api/merchant'
import { getTransferRecord, getTransferRecordDetails, getTransferOperated, getTransferAgent } from '@/api/gameReport'

import { useStore } from '@/stores/index'
const indexStore = useStore()

const data = reactive({
  query: {
    page: 1,
    size: 50,
    agent_id: -1,
    operated_id: -1,
    is_usdt_show: false,
    date: [getDateDay(0), getDateDay(0)]
  },
  list: [],
  total: 0,
  dayIndex: 1,
  fields: [
    { label: '日期', prop: 'date', width: '200', visible: true },
    { label: '商户昵称', prop: 'agent_id', width: '180', visible: true, tips: '商户的名称' },
    { label: '币种', prop: 'currency', width: '180', visible: true, tips: '商户游戏结算所使用的货币，不轻易更改，创建商户时的信息设定' },
    { label: '增加额度', prop: 'add_amount', width: '', visible: true, tips: '商户给玩家增加钱包额度数量' },
    { label: '扣除额度', prop: 'subtract_amount', width: '', visible: true, tips: '商户给玩家扣除钱包额度数量' },
    { label: '有效消耗额度', prop: 'consumption', width: '', visible: true, tips: '商户的玩家在游戏内消耗的钱包额度数量；增加-扣除' },
    { label: '转账用户数量', prop: 'count_user', width: '', visible: true, tips: '商户在筛选日期内的所有转账用户数量' },
    { label: '转账记录数量', prop: 'count', width: '', visible: true, tips: '商户在筛选日期内的所有转账次数' },
    { label: '转账失败条数', prop: 'fail_count', width: '', visible: true, tips: '商户在转账记录中状态为失败的数量' },
  ],
  dialogVisible: false,
  isShowDetails: false,
  isUserDetails: false,
  checkedItem: {} as any,
  checkedUserItem: {} as any,
  listDetails: [],
  totalDetails: 0,
  fieldDetails: [
    { label: '日期', prop: 'date', width: '200', visible: true },
    { label: '平台ID', prop: 'account3d_id', width: '', visible: true, tips: '玩家ID编号，唯一' },
    { label: '平台昵称', prop: 'account3d', width: '', visible: true, tips: '玩家名称' },
    { label: '增加额度', prop: 'add_amount', width: '', visible: true, tips: '商户给玩家增加钱包额度数量' },
    { label: '扣除额度', prop: 'subtract_amount', width: '', visible: true, tips: '商户给玩家扣除钱包额度数量' },
    { label: '有效消耗额度', prop: 'consumption', width: '', visible: true, tips: '商户的玩家在游戏内消耗的钱包额度数量；增加-扣除' },
    { label: '转账记录数量', prop: 'count', width: '', visible: true, tips: '商户在筛选日期内的所有转账次数' },
    { label: '转账失败条数', prop: 'fail_count', width: '', visible: true, tips: '商户在转账记录中状态为失败的数量' },
  ],
  OperatedArray:[] as any[],
  commercialArray:[] as any[]
})

onMounted(async () => {
  getSearchOperatedList(-1)
  getSearchAgentList(-1)
  getSearchList()
})

const getSearchList = async (type?: string) => {
  if(!data.isShowDetails){
    indexStore.setPageLoading(true)
  }else{
    indexStore.setModuleLoading(true)
  }
  let query = JSON.parse(JSON.stringify(data.query));
  query = setTimeValue(query)
  if (type && type == 'export') {
    query.size = 10000
  }
  let exchange = 1;
  let res = !data.isShowDetails ? await getTransferRecord(query) : await getTransferRecordDetails({
    page: query.page,
    size: query.size,
    agent_id: data.checkedItem.agent_id,
    start_time: query.start_time,
    end_time: query.end_time,
  })
  let resData = !data.isShowDetails ? res.data: res.data.list
  resData?.forEach((item: any) => {
    item.date = data.query.date[0] + ' ~ ' + data.query.date[1]
    item.add_amount = BigWan(item.add_amount)
    item.subtract_amount = BigWan(item.subtract_amount)
    // 汇率换算
    if (data.query.is_usdt_show) {
      exchange = CurrencyExchange(item.agent_id)
      item.add_amount = BigTimes(item.add_amount,data.checkedItem.usdt_rate?data.checkedItem.usdt_rate:item.usdt_rate)
      item.subtract_amount = BigTimes(item.subtract_amount,data.checkedItem.usdt_rate?data.checkedItem.usdt_rate:item.usdt_rate)
    }
    item.consumption = BigMinus(item.add_amount,item.subtract_amount)
    // 货币
    item.currency = AgentCurrency(item.agent_id)
  })
  // 导出
  if (type && type == 'export') {
    getExport(res.data.list)
    return
  }
  if(!data.isShowDetails){
    data.list = res.data
  }else{
    data.listDetails = res.data.list
    data.totalDetails = res.data.total
  }
}

// 设置快捷查询时间
const changeTime = throttle((type: number) => {
  if (data.dayIndex == type) return false
  data.dayIndex = type
  switch (type) {
    case 1:
      data.query.date = [getDateDay(0), getDateDay(0)]
      break;
    case 2:
      data.query.date = [getDateDay(-1), getDateDay(-1)]
      break;
    case 3:
      data.query.date = getWeek(-1)
      break;
    case 4:
      data.query.date = getWeek(0)
      break;
    case 5:
      data.query.date = getMonth(0)
      break;
    case 6:
      data.query.date = getMonth(-1)
      break;
  }
  getSearchList()
}, 2000)

// 详情
const checkDetails = async (row: any) => {
  data.isShowDetails = true
  data.checkedItem = row
  getSearchList()
}

// 选择总代-查询总代
const getSearchOperatedList = async (id: number) => {
  let res = await getTransferOperated({ })
  data.OperatedArray = []
  res.data.forEach((item:any)=> {
    data.OperatedArray.push({
      label: item.operator_name, value: item.id, type:item.operator_type, currency: item.is_multi_currency
    })
  });
}
// 选择总代-查询总代下所有商户
const getSearchAgentList = async (id: number) => {
  data.query.agent_id = -1
  let res = await getTransferAgent({ operated_id: id, api_type:1 })
  data.commercialArray = []
  res.data.forEach((item:any)=> {
    data.commercialArray.push({
      label: item.agent_name, value: item.id, type:item.agent_type, currency: item.currency_id
    })
  });
}

// 选择商户-查询总代
const getSearchAgentOperatedList = async (id: number) => {
  if(!indexStore.is_general_agent){
    if(id != -1){
      let agent = await getGeneralAgent({ agent_id: id })
      data.query.operated_id = agent.data.id
      let operated = await getTransferAgent({ operated_id: agent.data.id })
      data.commercialArray = []
      operated.data.forEach((item:any)=> {
        data.commercialArray.push({
          label: item.agent_name, value: item.id, type:item.agent_type, currency: item.currency_id
        })
      })
    }
  }
}

// 查看玩家信息
const checkUser = async (row: any) => {
  // uid
  data.checkedUserItem = row
  data.isUserDetails = true
}

// 导出
const getExport = async (dataList: any) => {
  let header: string[] = []
  let list: never[][] = []

  data.fields.forEach((item) => {
    header.push(item.label)
  })

  dataList.forEach((item: { [x: string]: any }, index: any) => {
    let arr: never[] = []
    data.fields.forEach((x) => {
      switch (x.prop) {
        case 'date':
          arr.push(data.query.date[0] + ' ~ ' + data.query.date[1] as never)
          break
        case 'agent_id':
          arr.push(selectToLabel(indexStore.agentArray, item[x.prop]) as never)
          break
        case 'currency':
          arr.push(AgentCurrency(item['agent_id']) as never)
          break
        default:
          arr.push(item[x.prop] as never)
          break
      }
    })
    list.push(arr)
  })
  exportToExcel(list, header, '转账钱包汇总')
}

// 修改页数
const changeSize = (val: number) => {
  data.query.size = val
}

const changePage = (val: number) => {
  data.query.page = val
  getSearchList()
}

// 重置表头
const resetData = (val: any) => {
  data.fields = val
}

// 重置
const onHideDetails = (show: boolean) => {
  data.isUserDetails = false
  data.query.page = 1
  data.query.size = 50
  if (show) {
    data.dayIndex == 1
    data.commercialArray = [] as any[]
    data.query = {
      page: 1,
      size: 50,
      agent_id: -1,
      operated_id: -1,
      is_usdt_show: false,
      date: [getDateDay(0), getDateDay(0)]
    }
    getSearchList()
    getSearchAgentList(-1)
  }
}
</script>

<style scoped lang="scss">
.formItem500 {
  width: 500px;
}
</style>